<?php
/**
 * Created by PhpStorm.
 * User: zyark
 * Date: 2017/8/15
 * Time: 16:45
 */

namespace Admin\Logic;


use Common\Utils\Constants;
use Common\Utils\TemplateUtils;
use Think\Exception;
use Think\Log;

class RoomLogic
{
    /**
     * 审核解散记录
     * @param $remark string 备注
     * @param $log_id int 记录id
     * @param $verify_type int 审核类型 1通过审核 2不通过审核
     * @param $is_poundage int 是否需要手续费
     * @return int 0该记录不能审核 1审核成功 2审核失败 3用户积分不足 4当前房间不能解散
     */
    public function verifyDissolveLog($remark,$log_id,$verify_type,$is_poundage){
        $model = M();
        $model->startTrans();
        $log =  $model->table('t_dissolve_log')->where(array('id'=>$log_id))->find();
        if($log['verify'] != Constants::VERIFY_STATUS_IN){//审核中
            return 0;
        }
        try{

            $room = $model->table('t_room')->where(array('id'=>$log['room_id']))->find();
            if($room['status'] != Constants::ROOM_STATUS_WAIT){
                return 4;
            }
            if($verify_type == 2){//不通过审核
                $model->table('t_dissolve_log')->where(array('id'=>$log_id))->setField('verify',Constants::VERIFY_STATUS_FAIL);
                $type = 0;
            }else{
                //返回金币钻石
                $this->returnMoney($room,$model);
                //通过审核
                $model->table('t_dissolve_log')->where(array('id'=>$log_id))->setField('verify',Constants::VERIFY_STATUS_SUCCESS);
                $model->table('t_room')->where(array('id'=>$log['room_id']))->setField('status',Constants::ROOM_STATUS_DISBANDED);
                $model->table('t_match_log')->where(array('room_id'=>$log['room_id']))->setField('status',Constants::MATCH_CANCEL);
                if($is_poundage == 1){
                    $status = $this->deductionFee($room,$model);
                    if($status != 1){
                        return $status;
                    }
                }
                $type = 1;
            }
            $message_remark = '';
            if($type == 0){
               $message_remark = $remark;
            }
            $model->table('t_dissolve_log')->where(array('id'=>$log_id))->setField('sys_remark',$remark);
            $model->commit();
            $this->sendDissolveSuccess($room['user_id'],$message_remark,$log['room_id'],$type);
            $this->sendDissolveSuccess($room['opponent_id'],$message_remark,$log['room_id'],$type);
            return 1;
        }catch (Exception $e){
            $model->rollback();
            return 2;
        }
    }

    /**
     * 扣除手续费
     * @param $room array 所属房间
     * @param $payer 0擂主 1打擂者
     * @param $model
     * @return int 1成功 2钻石不足 3金币不足
     */
    private function deductionFee($room,$payer,$model){
        //扣除手续费
        //获取解散房间手续费 百分比
        if($payer == 0) {
            $user_id = $room['user_id'];
        }else{
            $user_id = $room['opponent_id'];
        }
        if($room['money_type'] == Constants::MONEY_TYPE_GOLD){
            $name = Constants::CONFIG_DISBANDED_GOLD_NUMBER;
        }else{
            $name = Constants::CONFIG_DISBANDED_INTEGRAL_NUMBER;
        }
        $config = $model->table('t_config')->where(array('name'=>$name))->find();
//                    $room = $model->table('t_room')->where(array('id'=>$log['room_id']))->find();
        if(is_numeric($config['value']) && $config['value'] > 0) {//扣除手续费
            $user = $model->table('t_user')->where(array('id' => $user_id))->find();
            $money = $room['integral'] * $config['value'];
            if($room['money_type'] == Constants::MONEY_TYPE_GOLD){
                if($user['gold'] < $money){
                    return 3;//金币不足
                }
                $model->table('t_user')->where(array('id' => $user_id))->setDec('gold', $money);
                $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
            }else{
                if ($user['integral'] < $money) {
                    return 2;
                }
                $model->table('t_user')->where(array('id' => $user_id))->setDec('integral', $money);
                $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('integral');
            }
            $moneyLogic = new MoneyLogLogic();
            $moneyLogic->saveMoneyLog($money,
                $currentMoney,
                Constants::MONEY_SOURCE_POUNDAGE,
                Constants::PUT_TYPE_OUT,
                '解散房间扣除手续费',$user['id'],$room['money_type'],$model);
        }
        return 1;
    }

    //通过指定房间 返回金币或钻石
    private function returnMoney($room,$model){
        $money = $room['integral'];
        $this->returnMoneyToUser($room['money_type'],$room['user_id'],$money,$model);
        if(!empty($room['opponent_id'])){
            $this->returnMoneyToUser($room['money_type'],$room['opponent_id'],$money,$model);
        }
    }

    /**
     * 返回钻石或金币给用户
     * @param $money_type
     * @param $user_id
     * @param $money
     * @param $model
     */
    private function returnMoneyToUser($money_type,$user_id,$money,$model){
        if($money_type == Constants::MONEY_TYPE_GOLD){
            $model->table('t_user')->where(array('id' => $user_id))->setInc('gold', $money);
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('gold');
            $type = '金币';
        }else{
            $model->table('t_user')->where(array('id' => $user_id))->setInc('integral', $money);
            $currentMoney = $model->table('t_user')->where(array('id' => $user_id))->getField('integral');
            $type = '钻石';
        }
        $remark = '解散房间返回'.$type;
        $moneyLogic = new MoneyLogLogic();
        $moneyLogic->saveMoneyLog($money,
            $currentMoney,
            Constants::MONEY_SOURCE_DISSOLVE,
            Constants::PUT_TYPE_IN,
            $remark,$user_id,$money_type,$model);
    }


    /**
     * 管理员直接解散房间
     * @param $room_id int 房间id
     * @param $remark string 备注
     * @param $is_poundage int 是否需要手续费
     * @param $payer int 0擂主 1打擂者
     * @return int 0失败 1成功 2该房间已经解散  3已经结束 4钻石不足 5金币不足 6该房间不存在打擂者
     */
    public function dissolve($room_id,$remark,$is_poundage,$payer){
        $model = M();
        $model->startTrans();
        try{
            $room = $model->table('t_room')->where(array('id'=>$room_id))->find();
            if($room['status'] == Constants::ROOM_STATUS_DISBANDED){
                return 2;
            }
            if( $room['status']== Constants::ROOM_STATUS_END){
                return 3;
            }
            //返回金币钻石
            $this->returnMoney($room,$model);
            if($is_poundage == 1){
                if($payer == 1){//如果是打擂者 判断打擂者是否存在
                    if(empty($room['opponent_id'])){
                        return 6;//该房间不存在打擂者
                    }
                }
                $status = $this->deductionFee($room,$payer,$model);
                if($status == 2){
                    return 4;//钻石不足
                }else if($status == 3){
                    return 5;//金币不足
                }
            }
            //添加解散记录
            $this->addDissolveLog($remark,$room_id,$room['user_id'],$model);
            $model->table('t_room')->where(array('id'=>$room_id))->setField('status',Constants::ROOM_STATUS_DISBANDED);
            $model->table('t_match_log')->where(array('room_id'=>$room_id))->setField('status',Constants::MATCH_CANCEL);
            $this->sendDissolveSuccess($room['user_id'],'',$room_id,1);
            $this->sendDissolveSuccess($room['opponent_id'],'',$room_id,1);
//            $model->table('t_dissolve_log')->where(array('id'=>$log_id))->setField('sys_remark',$remark);
            $model->commit();
            return 1;
        }catch (Exception $e){
            $model->rollback();
            return 0;
        }
    }

    //发送消息
    private function sendDissolveSuccess($user_id,$remark,$room_id,$type){
        $openid = D('User')->where(array('id'=>$user_id))->getField('openid');
        $utils = new TemplateUtils();
        $utils->sendDisbandedSuccessMessage($openid,$remark,$room_id,$type);
    }

    private function addDissolveLog($remark,$room_id,$user_id,$model){
        $log['sys_remark'] = $remark;
        $log['room_id'] = $room_id;
        $log['user_id'] = $user_id;
        $log['verify'] = 1;
        $log['create_time'] = time();
        $model->table('t_dissolve_log')->add($log);
    }

    /**
     * 解散规定时间内未开始的所有房间
     * @return int status 0失败 1成功 2配置错误
     */
    public function dissolveAll(){
        $roomList = D('Room')->where(array('status'=>Constants::ROOM_STATUS_WAIT))->select();
        $model = M();
        $model->startTrans();
        try{
            $config = $model->table('t_config')->where(array('name'=>Constants::CONFIG_DISBANDED_ROOM_TIME))->find();
            $time = $config['value'];
            if(!is_numeric($time) || $time<0) {
                return 2;
            }
            $now = time();
            foreach ($roomList as $key=>$value){
                $time_off =intval(($now - $value['create_time'] )/60);
                if($time_off < $time){
                    continue;
                }
                //返回金币钻石
                $this->returnMoney($value,$model);
                $remark = '系统解散未进行比赛的房间';
                $this->addDissolveLog($remark,$value['id'],$value['user_id'],$model);
                $model->table('t_room')->where(array('id'=>$value['id']))->setField('status',Constants::ROOM_STATUS_DISBANDED);
                $model->table('t_match_log')->where(array('room_id'=>$value['id']))->setField('status',Constants::MATCH_CANCEL);
                $this->sendDissolveSuccess($value['user_id'],'',$value['id'],1);
//                $this->sendDissolveSuccess($value['opponent_id'],'',$value['room_id'],1);
            }
            $model->commit();
            return 1;
        }catch (Exception $e){
            Log::write("dissolveAll---:".$e->getMessage());
            $model->rollback();
            return 0;
        }
    }

}